import { platform } from "@/util/platform";

async function chooseFile(props: ChooseFile.IChooseFileProps) {
  let file;
  switch (props.type) {
    case "img": {
      file = await chooseImageFile();
      break;
    }
    case "audio": {
      file = await chooseAudioFile();
      break;
    }
    case "video": {
      file = await chooseVideoFile();
      break;
    }
  }
  return file;
}

async function chooseImageFile() {
  const obj = { name: "", path: "", size: "", width: "", height: "" };
  const file = (await uni.chooseImage({ count: 1 })) as any;
  if (platform !== "H5") {
    const res = (await uni.compressImage({ src: file.tempFiles[0].path })) as any;
    obj.path = res.tempFilePath;
    const info = (await uni.getImageInfo({ src: obj.path })) as any;
    const size = (await uni.getFileInfo({ filePath: obj.path })) as any;
    obj.size = size.size;
    obj.width = info.width;
    obj.height = info.height;
    return obj;
  } else {
    return file;
  }
}
async function chooseAudioFile() {
  let file;
  switch (platform) {
    case "H5": {
      file = await uni.chooseFile({ count: 1, type: "all", extension: [".mp3"] });
      break;
    }
    case "MP-WEIXIN": {
      file = await wx.chooseMessageFile({ count: 1, type: "file", extension: [".mp3"] });
      break;
    }
  }
  const fileName = file.tempFiles[0].name;
  if (fileName.endsWith(".mp3")) {
    file = file.tempFiles[0];
  } else {
    uni.showToast({ title: "请选择 .mp3 文件", icon: "none", duration: 2000 });
    file = { name: "", path: "", size: "" };
  }
  return file;
}
async function chooseVideoFile() {
  let obj = { name: "", path: "", size: "" };
  const file = (await uni.chooseVideo({ extension: ["mp4"] })) as any;
  const { tempFilePath, size } = file;
  return { ...obj, path: tempFilePath, size };
}

export { chooseFile };
